<template>
    <div>
        <vxe-toolbar custom ref="toolbarRef">
            <template #buttons>
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        v-if="permission.customer_add && this.editable"
                        @click="handleAdd"
                >添 加
                </el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           v-if="(permission.customer_add || permission.customer_edit) && this.editable"
                           @click="handleDelete">下 架
                </el-button>
            </template>
            <template #tools>

                <el-tooltip content="清空筛选" placement="top">
                    <vxe-button  icon="vxe-icon-delete" class="tool-btn" @click="$refs.tableRef.clearFilter()" circle></vxe-button>
                </el-tooltip>

                <vxe-button icon="vxe-icon-refresh" class="tool-btn" @click="refresh" circle
                            style="margin-right: 12px;"></vxe-button>
            </template>
        </vxe-toolbar>
        <vxe-grid ref="grid"
                  v-bind="gridOptions"
                  class="mytable-scrollbar"
                  size="medium"
                  @checkbox-change="selectionChange"
                  @checkbox-all="selectionChange"
                  @edit-closed="editClosedEvent"
                  @edit-actived="editActivedEvent"
                  :data="data"
                  :keyboardConfig="{isEdit:true}"
                  :tooltip-config="{ zIndex: 9999 }"
                  :scroll-y="{enabled: true, gt: 10}"
                  :edit-config="{
                  trigger: 'click',
                  mode: 'row',
                  showStatus: true,
                  showIcon: true,
                  autoClear:true,
                  beforeEditMethod: beforeEdit}">
            <template #bankId_edit="scope">
                <el-select v-model="scope.row.bankId"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择公司简称"
                           @change="handleSelectBank"
                           type="string" transfer>
                    <el-option
                            v-for="item in bankByRmbList"
                            :key="item.id"
                            :value="item.id"
                            :label="item.shortName"/>
                </el-select>
            </template>
            <template #bankId_default="scope">
                <span>{{formatBank(scope.row.bankId)}}</span>
            </template>

            <template #fullBox_edit="scope">
                <el-select v-model="scope.row.fullBox"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择是否整箱开单"
                           type="string" transfer>
                    <el-option value="是" label="是"/>
                    <el-option value="否" label="否"/>
                </el-select>
            </template>
            <template #fullBox_default="scope">
                <span>{{scope.row.fullBox}}</span>
            </template>

            <template #rmb_default="scope">
                <span>{{formatRmb(scope.row.rmb)}}</span>
            </template>
            <template #approveStatus_edit="scope">
                <el-select v-model="scope.row.approveStatus"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择审核状态"
                           type="string" transfer>
                    <el-option
                            v-for="item in approveStatusDic"
                            :key="item.dictKey"
                            :value="item.dictKey"
                            :label="item.dictValue"/>
                </el-select>
            </template>
            <template #approveStatus_default="scope">
                <el-tag :type="scope.row.approveStatus =='Draft' ? 'danger' : 'success'">
                    {{formatApproveStatus(scope.row.approveStatus)}}
                </el-tag>
            </template>
            <template #materialType_edit="scope">
                <el-select v-model="scope.row.materialType"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择类别"
                           type="string" transfer>
                    <el-option
                            v-for="item in materialTypeDic"
                            :key="item.dictKey"
                            :value="item.dictKey"
                            :label="item.dictValue"/>
                </el-select>
            </template>
            <template #materialType_default="scope">
                <span>{{formatMaterialType(scope.row.materialType)}}</span>
            </template>
            <template #seriesNo_default="scope">
                <span>{{formatSeriesNo(scope.row.seriesNo)}}</span>
            </template>
            <template #programName_default="scope">
                <span>{{formatProgramName(scope.row.programName)}}</span>
            </template>
            <template #btn_default="scope">
                <template v-if="this.editable">
                    <el-tooltip content="移除" placement="top">
                        <el-button
                                icon="el-icon-delete"
                                link
                                size="small"
                                type="primary"
                                @click="rowDel(scope.row)"
                        ></el-button>
                    </el-tooltip>
                </template>
            </template>
        </vxe-grid>
<!--        <select-material ref="selectMaterial" @setMaterialList="setMaterialList"></select-material>-->
      <select-sales-price ref="selectSalesPrice" @setMaterialList="setMaterialList"></select-sales-price>
    </div>
</template>

<script>
    import {getList, getDetail, add, update, remove, audit, findList} from "@/api/anwise/customer/customer_material";
    import {bankDetail} from "@/api/anwise/bank_info";
    import {mapGetters} from "vuex";
    import SelectMaterial from '@/views/anwise/customer/components/select_material.vue';
    import selectSalesPrice from '@/views/anwise/customer/components/select_sales_price.vue';
    import {Pattern} from '@/utils/validate.js';
    import {getDictionary} from "@/api/system/dictbiz";
    import {bankSelect} from "@/api/anwise/bank_info";
    import {materialSeriesSelect} from "@/api/anwise/material/material_series";
    import {selectCustomerGroup} from "@/api/anwise/material/customer_group";

    export default {
        components: {
            SelectMaterial,
          selectSalesPrice
        },
        data() {
            return {
                editable: true,
                customerId: '',
                form: {},
                query: {},
                loading: false,
                // page: {
                //     pageSize: 2,
                //     currentPage: 1,
                //     // total: 0
                // },
                selectionList: [],
                validEmptyRules: {
                    price: [
                        {required: true, message: "请输入单价/100"},
                        {pattern: Pattern.amount_w, message: '请输入数字'}
                    ],
                    bankId: [
                        {required: true, message: "请选择公司简称"}
                    ]
                },
                bankList: [],
                bankByRmbList:[],
                rmbDic: [],
                approveStatusDic: [],
                materialTypeDic: [],
                materialSeriesSelect: [],
                programNameSelect: [],
                gridOptions: {
                    height: '400px',
                    border: true,
                    showOverflow: true,
                    keepSource: true,
                    size: "medium",
                    rowConfig: {
                        keyField: 'id',
                        isHover: true
                    },
                    columnConfig: {
                        resizable: true
                    },
                    // editRules: ,
                    columns: [
                        {type: 'checkbox', width: 50, fixed:'left', visible: true},
                        // {type: 'seq', width: 50, fixed:'left', align: "center"},
                        {
                            title: "物料编号",
                            field: "materialNo",
                            minWidth: 120,
                            fixed:'left',
                            sortable: true,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                            // editRender: {name: 'input', attrs: {placeholder: '请输入物料编号'}}
                        },
                        {
                            title: "客户条码",
                            field: "barCode",
                            sortable: true,
                            fixed:'left',
                            minWidth: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                            // editRender: {name: 'input', attrs: {placeholder: '请输入客户条码'}}
                        },
                        {
                            title: "物料名称",
                            field: "materialName",
                            minWidth: 120,
                            sortable: true,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                            // editRender: {name: 'input', attrs: {placeholder: '请输入物料名称'}}
                        },
                      {
                        title: "品牌",
                        field: "programName",
                        sortable: true,
                        width: 120,
                        slots: {default: 'programName_default'},
                        filters: [{ data: '' }],
                        filterRender: { name: 'FilterInput'}
                      },
                        {
                            title: "单价/100",
                            field: "salesPrice",
                            minWidth: 150,
                            sortable: true,
                            // editRender: {name: 'input', attrs: {placeholder: '请输入单价/100'}},
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "是否整箱开单",
                            field: "fullBox",
                            minWidth: 150,
                            sortable: true,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'fullBox_edit', default: 'fullBox_default'}
                        },
                        {
                            title: "公司简称",
                            field: "bankId",
                            sortable: true,
                            width: 200,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'bankId_edit', default: 'bankId_default'}
                        },
                        {
                            title: "币别",
                            field: "rmb",
                            sortable: true,
                            width: 120,
                            disabled: true,
                            // editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {default: 'rmb_default'}
                        },
                        {
                            title: "审批状态",
                            field: "approveStatus",
                            // dicUrl: "/blade-system/dict-biz/dictionary?code=approve_status",
                            sortable: true,
                            width: 150,
                            // editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {default: 'approveStatus_default'},
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "类别",
                            field: "materialType",
                            sortable: true,
                            width: 120,
                            // dicUrl: "/blade-system/dict-biz/dictionary?code=material_s_type",
                            // editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {default: 'materialType_default'},
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "海关编码",
                            field: "mateGroup",
                            // editRender: {name: 'input', attrs: {placeholder: '海关编码'}},
                            sortable: true,
                            width: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "系列代码",
                            field: "seriesNo",
                            // dicUrl: '/api/blade-anwise/material_series/select',
                            slots: {default: 'seriesNo_default'},
                            sortable: true,
                            width: 120,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "审批人",
                            field: "approveName",
                            sortable: true,
                            width: 120,
                        },
                        {
                            title: "审批时间",
                            field: "approveDate",
                            sortable: true,
                            width: 120,
                        },
                        {
                            title: "上架人员",
                            field: "operName",
                            sortable: true,
                            width: 120,
                        },
                        {
                            title: "上架时间",
                            field: "operDate",
                            sortable: true,
                            width: 120,
                        },
                        {
                            field: 'btn',
                            title: '操作',
                            minWidth: 120,
                            align: "center",
                            fixed: "right",
                            visible: true,
                            slots: {default: 'btn_default'}
                        }
                        // {
                        //   title: "停用标识",
                        //   field: "stopComm",
                        //     type: "select",
                        //     dicUrl: "/blade-system/dict-biz/dictionary?code=biz_yes_no",
                        //     filterable: true,
                        //     overHidden: true,
                        //     sortable: true,
                        //     width:150,
                        //     props: {
                        //         label: 'dictValue',
                        //         value: 'dictKey',
                        //     },
                        //     dataType: 'string',
                        //   rules: [{
                        //     required: true,
                        //     message: "请输入停用标识",
                        //     trigger: "blur"
                        //   }],
                        // },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.customer_material_add, false),
                    viewBtn: this.validData(this.permission.customer_material_view, false),
                    delBtn: this.validData(this.permission.customer_material_delete, false),
                    editBtn: this.validData(this.permission.customer_material_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.selectDicData();
                this.init();
            })
        },
        methods: {
            init() {
                this.$refs.grid.connect(this.$refs.toolbarRef);
                this.gridOptions.editRules = this.validEmptyRules;
            },
            editClosedEvent(row) {//关闭单元格事件
                const $table = this.$refs.grid;
                $table.clearValidate();
            },
            editActivedEvent(row) {//激活单元格事件
                // this.gridOptions.editRules = this.validRules;
              console.log(row.row)
              bankSelect({rmb:row.row.rmb}).then(res => {
                this.bankByRmbList = res.data.data;
              })
            },
            beforeEdit(row) {
                if (row.row.approveStatus === "Draft" && this.editable) {
                    return true
                }
                return false
            },
            selectDicData() {
                bankSelect().then(res => {
                    this.bankList = res.data.data;
                })
                getDictionary({code: "rmb"}).then(res => {
                    this.rmbDic = res.data.data;
                })
                getDictionary({code: "approve_status"}).then(res => {
                    this.approveStatusDic = res.data.data;
                })
                getDictionary({code: "material_s_type"}).then(res => {
                    this.materialTypeDic = res.data.data;
                    let dicList=[];
                    this.materialTypeDic.forEach(res=>{
                        let dic={};
                        dic.label = res.dictKey;
                        dic.value = res.dictValue;
                        dicList.push(dic);
                    })
                })
                materialSeriesSelect().then(res => {
                    this.materialSeriesSelect = res.data.data;
                    let dicList=[];
                    this.materialSeriesSelect.forEach(res=>{
                        let dic={};
                        dic.label = res.seriesNo;
                        dic.value = res.id;
                        dicList.push(dic);
                    })
                })
                selectCustomerGroup().then(res => {
                    this.programNameSelect = res.data.data;
                    let dicList=[];
                    this.programNameSelect.forEach(res=>{
                        let dic={};
                        dic.label = res.programName;
                        dic.value = res.id;
                        dicList.push(dic);
                    })
                })
                let dicList=[];
                let dic={};
                dic.label ='Draft';
                dic.value = 'Draft';
                dicList.push(dic);
                let dic1={};
                dic1.label ='Approved';
                dic1.value = 'Approved';
                dicList.push(dic1);
            },
            formatBank(id) {
                let value = "";
                this.bankList.forEach(res => {
                    if (res.id === id) {
                        value = res.shortName
                    }
                })
                return value;
            },
            formatRmb(key) {
                let value = "";
                this.rmbDic.forEach(res => {
                    if (res.dictKey === key) {
                        value = res.dictValue
                    }
                })
                return value;
            },
            formatApproveStatus(key) {
                let value = "";
                this.approveStatusDic.forEach(res => {
                    if (res.dictKey === key) {
                        value = res.dictValue
                    }
                })
                return value;
            },
            formatMaterialType(key) {
                let value = "";
                this.materialTypeDic.forEach(res => {
                    if (res.dictKey === key) {
                        value = res.dictValue
                    }
                })
                return value;
            },
            formatSeriesNo(id) {
                let value = "";
                this.materialSeriesSelect.forEach(res => {
                    if (res.id === id) {
                        value = res.seriesNo
                    }
                })
                return value;
            },
            formatProgramName(programName) {
                let value = "";
                this.programNameSelect.forEach(res => {
                    if (res.programName === programName) {
                        value = res.programName
                    }
                })
                return value;
            },
            refresh() {
                this.page = {
                    pageSize: 20,
                    currentPage: 1,
                }
                this.query = {}
                this.query.customerId = this.customerId
                this.onLoad(this.page)
            },
            isActiveStatus(row) {
                const $table = this.$refs.grid
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            handleSelectBank(e) {
                const $table = this.$refs.grid;
                if (e) {
                    bankDetail(e).then(res => {
                        if (res.data.success) {
                            $table.getEditRecord().row.rmb = res.data.data.rmb;
                        }
                    })
                }
            },
            handleAudit() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                audit(this.ids).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: res.data.msg || "操作成功!"
                        });
                    }
                })
            },
            handleAdd() {
                if (this.$refs.grid.getEditRecord()) {
                    return;
                }
                this.$refs.selectSalesPrice.showSelect(this.$refs.grid.getTableData().fullData);
            },
            setMaterialList(list) {
                let selectData = markRaw(list);
                selectData.forEach(item => {
                    if (!this.$refs.grid.getTableData().fullData.some((val) => (val.materialId == item.id && val.programName == item.programName))) {
                        let prodComplete ='否';
                        let stockComplete ='否';
                        let deliComplete ='否';
                        if (item.materialNo.startsWith('PHCOST')) {
                            prodComplete ='是';
                            stockComplete ='是';
                            deliComplete ='是';
                        }
                      console.log(item.id)
                        let mat = {
                            // id: '',
                            materialId: item.id,
                            materialNo: item.materialNo,
                            materialName: item.materialName,
                            materialType: item.type,
                            programName: item.programName,
                            price: item.price,
                          salesPrice: item.price,
                            rmb:item.rmb,
                            seriesNo: item.seriesNo,
                            mateGroup: item.mateGroup,
                            barCode: item.barCode,
                            approveStatus: 'Draft',
                            fullBox: item.fullBox,
                            prodComplete: prodComplete,
                            stockComplete:stockComplete,
                            deliComplete:deliComplete,
                            $cellEdit: true
                        }
                        // this.data.push(mat);
                        const obj = this.$refs.grid.insertAt(mat, -1);
                    }
                });
            },
            setData(id, editable) {
                this.customerId = id;
                this.editable = editable;
                if (id) {
                    this.onLoad(this.page)
                }
            },
            async rowDel(row) {
                const $table = this.$refs.grid;
                this.$confirm('确定将选择产品移除吗?', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    // this.data.forEach((res,index)=>{
                    //     if(res.materialId === row.materialId){
                    //         this.data.splice(index,1);
                    //     }
                    // })
                    $table.remove(row)
                }).then(() => {
                    this.$message({type: "success", message: "操作成功，保存后生效!"});
                })
            },
            handleDelete() {
                if (this.$refs.grid.getEditRecord()) {
                    return;
                }
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择产品下架吗?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.selectionList.forEach(item => {
                            item.approveStatus = 'Draft'
                            // return !this.selectionList.some((val)=> (val.materialNo == item.materialNo))
                        })
                        // return remove(this.ids);
                    })
                    .then(() => {
                        // this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功，保存后生效!"
                        });
                        this.$refs.grid.clearCheckboxRow();
                        // this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list.records;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.grid.clearCheckboxRow();
                // this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                const $table = this.$refs.grid;
                if (this.customerId) {
                    params.customerId = this.customerId;
                }else{
                    params.customerId = -1
                }
                let isEdit=false;
                $table.getTableData().tableData.forEach(res=>{
                    if(!res.id || res.id.includes("row")){
                        isEdit=true;
                        res.id = "";
                    }
                })
                if (isEdit || $table.getRemoveRecords().length>0 || $table.getUpdateRecords().length>0) {
                    this.$confirm("搜索会丢失本次新增/编辑/删除的数据，确定继续吗?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then(()=>{
                        findList(Object.assign(params, this.query)).then(res => {
                            const data = res.data.data;
                            this.data = data;
                            $table.loadData(this.data);
                            this.selectionClear();
                        });
                    })
                }else{
                    findList(Object.assign(params, this.query)).then(res => {
                        const data = res.data.data;
                        this.data = data;
                        $table.loadData(this.data);
                        this.selectionClear();
                    });
                }
            }
        }
    };
</script>

<style>
</style>
